package
{
	import com.xcopy.Screen;
	import fl.events.ComponentEvent;
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.MouseEvent;

	public class Slot25Machine extends Screen
	{
		public var process:Number                            = 0;
		// 目前機器的狀態
		public static const STATE_NONE:Number                = 0; // 機台未開啟
		public const STATE_PLAY:Number                       = 1; // 開啟，玩家可操作
		public const STATE_RUN:Number                        = 2; // 轉盤正在運作中
		public const STATE_HARD:Number                       = 3; // 轉盤運作完成展示（硬直）
		public const STATE_DEMO:Number                       = 4; // 轉盤運作完成展示
		public const STATE_FREE:Number                       = 5; // 正在進行小遊戲
		public const TIME_COLUMN_STEP:Number                 = 0.05; // 拉霸每行開始間隔時間
		public const TIME_SCROLL_STEP:Number                 = 0.40; // 卷軸連續增加間隔時間
		public const TIME_AUTO_STEP:Number                   = 0.05; // 自動下注調整間隔時間
		public const TIME_DEMO_STEP:Number                   = 1.20; // 自動展示間隔時間
		public const TIME_COIN_SPRAY:Number                  = 5.20; // 噴金幣時間
		public const TIME_COIN_SOUND:Number                  = 3.00; // 噴金幣時間
		public const SYMBOL_JACKPOT:Number                   = 9;
		// 目前選擇線數的下一個選擇，比如目前 3 線，按下【上】鈕，會跳到 5 線，（懶得用程式算了，直接用陣列指定，花點空間換時間）
		protected var _switchUpper:Array                     = [0, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20, 20, 20, 25, 25, 25,
			25, 25, 5];
		protected var _switchLower:Array                     = [0, 25, 25, 25, 25, 25, 5, 5, 5, 5, 5, 10, 10, 10, 10, 10, 15, 15, 15, 15, 15, 20, 20, 20,
			20, 20];
		protected var _columnMap:Array                       = [[2, 2, 2, 2, 2], [1, 1, 1, 1, 1], [3, 3, 3, 3, 3], [1, 2, 3, 2, 1], [3, 2, 1, 2, 3], [2,
			1, 1, 1, 2], [2, 3, 3, 3, 2], [1, 1, 2, 3, 3], [3, 3, 2, 1, 1], [2, 3, 2, 1, 2], [2, 1, 2, 3, 2], [1, 2, 2, 2, 1], [3, 2, 2, 2, 3], [1, 2,
			1, 2, 1], [3, 2, 3, 2, 3], [2, 2, 1, 2, 2], [2, 2, 3, 2, 2], [1, 1, 3, 1, 1], [3, 3, 1, 3, 3], [1, 3, 3, 3, 1], [3, 1, 1, 1, 3], [1, 3, 1,
			3, 1], [3, 1, 3, 1, 3], [2, 3, 1, 3, 2], [2, 1, 3, 1, 2]];
		// 設定連線彩金數值與播放動畫
		protected var _boxJackpot:DigitalBox                 = new DigitalBox(this);
		protected var _boxLine:DigitalBox                    = new DigitalBox(this);
		protected var _boxPrice:DigitalBox                   = new DigitalBox(this);
		protected var _boxTotal:DigitalBox                   = new DigitalBox(this);
		protected var _boxReward:DigitalBox                  = new DigitalBox(this);
		protected var _boxAuto:DigitalBox                    = new DigitalBox(this);
		protected var _boxSerial:DigitalBox                  = new DigitalBox(this);
		// 機台本身屬性及可視物件陣列
		protected var _state:Number                          = STATE_NONE; // 機台目前狀態
		protected var _slotColumns:Vector.<Slot25SlotColumn> = Vector.<Slot25SlotColumn>([]); // 轉盤陣列，1 至 5 號轉盤，由 0 開始
		protected var _slotRings:Vector.<MovieClip>          = Vector.<MovieClip>([]);
		protected var _slotLights:Vector.<MovieClip>         = Vector.<MovieClip>([]); // 燈號陣列，1 至 25 號燈，由 0 開始
		protected var _slotScrolls:Vector.<MovieClip>        = Vector.<MovieClip>([]); // 寶物陣列，1 至 5 號燈，由 0 開始
		protected var _slotLine:Slot25SlotLine               = new Slot25SlotLine(this); // 轉盤連線
		protected var _slotFree1:Slot25FreeGameGirl          = new Slot25FreeGameGirl(this); // 免費遊戲
		protected var _slotFree2:Slot25FreeGameJungle        = new Slot25FreeGameJungle(this); // 免費遊戲
		// 機台隱藏參數，比如壓幾線，一注下多少等等
		protected var _numLines:Number                       = 0; // 賭了幾線。1 表示只有 1 線，25 表示全壓了		
		protected var _numAuto:Number                        = 0; // 剩餘的自動壓注
		protected var _numPrice:Number                       = 0; // 一注賭資
		protected var _numScrolls:Number                     = 0; // 目前卷軸數量
		protected var _numScrollTarget:Number                = 0; // 目標卷軸數量
		protected var _inFreeGame:Boolean                    = false; // 是否正在小遊戲中
		protected var _isHolding:Boolean                     = false; // 是否已拉停
		// 調整自動下注使用的變數，因為那個不是按鈕，而是壓著就會自動增減
		protected var _autoUp:Boolean                        = false;
		protected var _autoDown:Boolean                      = false;
		protected var _autoStep:Number                       = 1;
		protected var _autoCount:Number                      = 0;
		protected var _autoBet:Boolean                       = false; // 停下後是否要再自動拉把
		// 拉霸的結果
		protected var _resultColumn:Array                    = [];
		protected var _resultSymbol:Array                    = [];
		protected var _resultCount:Array                     = [];
		protected var _resultLights:Array                    = [];
		protected var _resultHeart:Number                    = 0;
		protected var _resultWin:Number                      = 0;
		protected var _resultNow:Number                      = 0;
		protected var _resultRound:Number                    = 0; // 目前 demo 到第幾輪（只有第一輪會有音效）
		protected var _demoTotal:Number                      = 0; // 總共有幾個 demo（所有線，每條線，jackpot）
		protected var _demoCurrent:Number                    = 0; // 目前 demo 到第幾個
		protected var _demoSection:Array                     = []; // 每小節該播放的
		protected var _demoEffect:Number                     = 0; // demo 一開始的音效要用哪種，0 無 1 普通 2 jackpot 3 jackpot 大
		protected var _isGirlFree:Boolean                    = false; // 本次的拉霸結果是否是拜金女小遊戲的結果
		private var _table:Slot25Table;

		public function get table():Slot25Table
		{
			return _table;
		}

		public function get main():NewBridge_25LineSlot
		{
			return table.main;
		}

		public function get debug():Slot25Debugger
		{
			return main.debug;
		}

		public function get client():FGS18Processer
		{
			return main.client;
		}

		public function get core():Slot25Core
		{
			return main.core;
		}

		// =================================================== 建構子、初始化及屬性對
		// ===========================================================
		public function Slot25Machine(r:* = null)
		{
			super(r);
			_table = r as Slot25Table;
		}

		override public function set clip(mc:MovieClip):void
		{
			super.clip = mc;
			var i:Number = 0;
			var mv:MovieClip;
			// 數字燈箱對應
			_boxJackpot.clip = clip.oJackpot;
			_boxLine.clip = clip.oLine;
			_boxPrice.clip = clip.oPrice;
			_boxTotal.clip = clip.oTotal;
			_boxReward.clip = clip.oReward;
			_boxAuto.clip = clip.oAuto;
			_boxSerial.clip = clip.oSerial;
			switch (this.table.lobby.type)
			{
				case this.table.lobby.TYPE_GIRL: // 瘋狂拜金女
				{
					_slotFree1.clip = clip.oFreeGame;
					break;
				}
				case this.table.lobby.TYPE_JUNGLE: // 叢林探險
				{
					_slotFree2.clip = clip.oFreeGame;
					break;
				}
			}
			_slotFree1.addEventListener(_slotFree1.TERMINATE, onFreeGameOver);
			_slotFree2.addEventListener(_slotFree2.TERMINATE, onFreeGameOver);
			if (clip.hasOwnProperty('oRing1'))
			{
				for (i = 1; i <= 23; i++)
				{
					mv = clip.getChildByName('oRing' + i) as MovieClip;
					_slotRings.push(mv);
				}
			}
			// 壓線燈號對應
			for (i = 0; i < 25; i++)
			{
				mv = clip.getChildByName('oLight' + (i + 1)) as MovieClip;
				setClickEvent(mv, createCallBack(onLineClick, i + 1), true);
				_slotLights.push(mv);
			}
			// 五排轉盤對應
			for (i = 0; i < 5; i++)
			{
				mv = clip.oWheel.getChildByName('oColumn' + (i + 1)) as MovieClip;
				_slotColumns[i] = new Slot25SlotColumn(this);
				_slotColumns[i].clip = mv;
				_slotColumns[i].index = i;
				_slotColumns[i].addEventListener(Slot25SlotColumn.EVENT_STOP, onColumnStop);
				_slotColumns[i].addEventListener(Slot25SlotColumn.EVENT_STOCK, onColumnStock);
				_slotColumns[i].addEventListener(Slot25SlotColumn.EVENT_RUN, onColumnRun);
					//_slotColumns[i].addEventListener(Slot25SlotColumn.EVENT_BREAK, onColumnBreak);
					//_slotColumns[i].addEventListener(Slot25SlotColumn.EVENT_DUCK, onColumnDuck);
			}
			for (i = 0; i < 5; i++)
			{
				mv = clip.getChildByName('oMadel' + (i + 1)) as MovieClip;
				_slotScrolls[i] = mv;
			}
			clip.txtStatus.text = '';
			_slotLine.clip = clip.oLineDemo;
			// 功能按鈕對應
			setClickEvent(clip.btnLineUp, createCallBack(onLineSwitch, 1));
			setClickEvent(clip.btnLineDown, createCallBack(onLineSwitch, 2));
			setClickEvent(clip.btnPriceUp, createCallBack(onPriceSwitch, 1));
			setClickEvent(clip.btnPriceDown, createCallBack(onPriceSwitch, 2));
			setClickEvent(clip.btnFull, onFullBet);
			setClickEvent(clip.btnStop, onStop);
			setClickEvent(clip.btnStart, onStartButton);
			setClickEvent(clip.btnLeave, reserveMachine);
			setClickEvent(clip.btnManual, onRule);
			clip.btnAutoUp.addEventListener(MouseEvent.MOUSE_DOWN, createCallBack(setAutoSwitch, 1, 1));
			clip.btnAutoUp.addEventListener(MouseEvent.MOUSE_OUT, createCallBack(setAutoSwitch, 1, 2));
			clip.btnAutoUp.addEventListener(MouseEvent.MOUSE_UP, createCallBack(setAutoSwitch, 1, 2));
			clip.btnAutoDown.addEventListener(MouseEvent.MOUSE_DOWN, createCallBack(setAutoSwitch, 2, 1));
			clip.btnAutoDown.addEventListener(MouseEvent.MOUSE_OUT, createCallBack(setAutoSwitch, 2, 2));
			clip.btnAutoDown.addEventListener(MouseEvent.MOUSE_UP, createCallBack(setAutoSwitch, 2, 2));
			clip.oFreeGame.visible = false;
			disable();
		}

		public function sendLeaveMachine(type:Number, pass:String):void
		{
			this.debug.print('>> C2S_ExitTable：[' + type + ', ' + pass + ']');
			this.client.C2S_ExitTable(type, pass);
		}

		// 在功能表列按下離坐，送出離開指令 。
		public function onRule(e:MouseEvent):void
		{
			this.table.rule.openRate();
		}

		// 在功能表列按下離坐，送出離開指令 。
		public function leaveMachine(e:MouseEvent):void
		{
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			sendLeaveMachine(0, '');
		}

		// 在功能表列按下保留。送出離開指令 。
		public function reserveMachine(e:MouseEvent):void
		{
			auto = 0;
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			this.table.rule.onClose();
			table.alert.addReserve(sendLeaveMachine);
		}

		public function set reward(n:Number):void
		{
			_boxReward.number = n;
		}

		public function get reward():Number
		{
			return _boxReward.number;
		}

		public function set isHolding(b:Boolean):void
		{
			_isHolding = b;
		}

		public function get isHolding():Boolean
		{
			return _isHolding;
		}

		public function set serial(n:Number):void
		{
			_boxSerial.serial = n;
		}

		public function get serial():Number
		{
			return _boxSerial.serial;
		}

		public function set state(n:Number):void
		{
			_state = n;
		}

		public function get state():Number
		{
			return _state;
		}

		public function set auto(n:Number):void
		{
			if (n < 0)
			{
				n = 0;
			}
			if (n > 9999)
			{
				n = 9999;
			}
			_numAuto = n;
			_boxAuto.number = n;
		}

		public function get auto():Number
		{
			return _numAuto;
		}

		public function get canPost():Boolean
		{
			return (clip.visible == false || (clip.visible == true && (state == STATE_PLAY || state == STATE_DEMO)));
		}

		// 目前賭了幾線的屬性對子，25 表示 25 線全壓
		public function set line(n:Number):void
		{
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			var i:Number = 0;
			_numLines = n;
			_boxLine.number = n;
			for (i = 0; i < 25; i++)
			{
				if (i < n)
				{
					_slotLights[i].gotoAndStop('Light');
				}
				else
				{
					_slotLights[i].gotoAndStop('Dark');
				}
			}
			_boxTotal.number = price * line;
		}

		public function get line():Number
		{
			return _numLines;
		}

		public function set price(n:Number):void
		{
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			_numPrice = n;
			if (_numPrice > 100)
			{
				_numPrice = 20;
			}
			if (_numPrice < 20)
			{
				_numPrice = 100;
			}
			_boxPrice.number = _numPrice;
			_boxTotal.number = price * line;
		}

		public function get price():Number
		{
			return _numPrice;
		}

		public function set jackpot(n:Number):void
		{
			_boxJackpot.target = n;
		}

		public function get jackpot():Number
		{
			return _boxJackpot.number;
		}

		public function demoRings():void
		{
			for each (var mc:MovieClip in _slotRings)
			{
				mc.play();
			}
		}

		public function demoLines(TotalLines:Array):void
		{
			var i:Number = 0;
			for (i = 0; i < 25; i++)
			{
				if (TotalLines.indexOf(i) >= 0)
				{
					_slotLights[i].gotoAndStop('Light');
				}
				else
				{
					_slotLights[i].gotoAndStop('Dark');
				}
			}
		}

		// 漸進顯示卷軸
		public function set scrollTarget(n:Number):void
		{
			if (_numScrollTarget == n)
			{
				return;
			}
			_numScrollTarget = n;
			addScroll();
		}

		public function addScroll():void
		{
			if (_numScrollTarget > _numScrolls)
			{
				playScroll(_numScrolls);
				_numScrolls++;
				addCaller(this, {time: TIME_SCROLL_STEP, count: 1, onUpdate: addScroll});
			}
		}

		// 直接指定目前的卷軸數量，直接顯示卷軸並設定 _numScrolls
		public function set scrolls(n:Number):void
		{
			_numScrolls = n;
			var i:Number = 0;
			for (i = 0; i < 5; i++)
			{
				if (i < n)
				{
					showScroll(i);
				}
				else
				{
					hideScroll(i);
				}
			}
		}

		public function get scrolls():Number
		{
			return _numScrolls;
		}

		public function playScroll(index:Number):void
		{
			this.table.playSound('1240');
			_slotScrolls[index].gotoAndPlay('Got');
		}

		public function showScroll(index:Number):void
		{
			_slotScrolls[index].gotoAndStop('Full');
		}

		public function hideScroll(index:Number):void
		{
			_slotScrolls[index].gotoAndStop('Empty');
		}

		// 儲存小遊戲結果先，待之後顯示結果後才會進小遊戲
		public function saveFreeJungle(data:Object):void
		{
			this.debug.print('儲存小遊戲結果先');
			_slotFree2.data = data;
		}

		public function saveFreeGirl(data:Object):void
		{
			_slotFree1.data = data;
		}

		public function onFreeGameOver(e:Event):void
		{
			scrolls = 0;
			if (this._isGirlFree) // 這個表示是拜金女小遊戲結束了
			{
				this._isGirlFree = false;
				this.core.gold += this._slotFree1.reward.number;
			}
			_inFreeGame = false;
			state = STATE_PLAY;
			popMessage();
			if (auto > 0 && _autoBet)
			{
				addCaller(this, {time: TIME_DEMO_STEP, count: 1, onUpdate: startBar});
			}
		}

		// 開啟機台
		public function onMachine(n:Number):void
		{
			var i:Number = 0;
			table.music = '';
			serial = n;
			state = STATE_PLAY;
			line = 25;
			price = 100;
			scrolls = 0;
			scrollTarget = 0;
			clip.btnStart.visible = true;
			_resultColumn = [];
			_resultSymbol = [];
			_resultCount = [];
			_resultHeart = 0;
			_resultWin = 0;
			_resultNow = 0;
			enable();
			for (i = 0; i < 5; i++)
			{
				_slotColumns[i].initColumn();
			}
		}

		public function offMachine():void
		{
			state = STATE_NONE;
			table.music = 'Lobby';
		}

		// 開始拉霸
		public function onResult(BarNo:Array, LineSymbols:Array, LineCount:Array, HeartCount:int, WinPoint:int, NowPoint:int):void
		{
			var i:Number               = 0;
			var extra:Number           = 0;
			var jackpots:Number        = 0;
			var jackpotThisLine:Number = 0;
			this.debug.print('\n\nnew result');
			this.debug.print('' + BarNo[0] + ',' + BarNo[1] + ',' + BarNo[2] + ',' + BarNo[3] + ',' + BarNo[4]);
			this.debug.print('' + BarNo[5] + ',' + BarNo[6] + ',' + BarNo[7] + ',' + BarNo[8] + ',' + BarNo[9]);
			this.debug.print('' + BarNo[10] + ',' + BarNo[11] + ',' + BarNo[12] + ',' + BarNo[13] + ',' + BarNo[14]);
			//（記下本次拉霸 server 傳來的結果）
			_resultColumn = BarNo;
			_resultSymbol = LineSymbols;
			_resultCount = LineCount;
			_resultHeart = HeartCount;
			_resultWin = WinPoint;
			_resultNow = NowPoint;
			_resultLights = [];
			_resultRound = 2;
			for (i = 0; i < 25; i++)
			{
				if (_resultCount[i] >= 3)
				{
					_resultLights.push(i);
				}
			}
			for (i = 0; i < 5; i++)
			{
				// 如果需要額外運轉，在此計算
				extra++;
				addCaller(this, {time: TIME_COLUMN_STEP * i, count: 1, onUpdate: _slotColumns[i].startFull, onUpdateParams: [BarNo[(i)], BarNo[(5 + i)],
							BarNo[(10 + i)], extra]});
				jackpotThisLine = 0;
				// 如果這行有 jackpot，則下一排增加時間
				if (BarNo[(i)] == 9)
				{
					jackpotThisLine++;
				}
				if (BarNo[(5 + i)] == 9)
				{
					jackpotThisLine++;
				}
				if (BarNo[(10 + i)] == 9)
				{
					jackpotThisLine++;
				}
				jackpots += jackpotThisLine;
				if (((i == 1) && (jackpots >= 2)) || ((i == 2) && (jackpotThisLine > 0) && (jackpots >= 2)))
				{
					extra += _slotColumns[0].DISTANCE_LENGTH_JACKPOT;
				}
			}
		}

		// =============================================== 按鈕點下後的反應函式
		// ================================================
		// 按下某個燈號，或是按下加減線的按鈕，向上或向下調整線數 5, 10, 15, 20, 25
		public function onLineClick(n:Number):void
		{
			this.table.playSound('1010');
			line = n;
		}

		public function onLineSwitch(way:Number):void
		{
			this.table.playSound('1000');
			line = (way == 1 ? _switchUpper[line] : _switchLower[line]);
		}

		// 向上或向下調一注金額
		public function onPriceSwitch(way:Number):void
		{
			this.table.playSound('1000');
			price += (way == 1 ? 20 : -20);
		}

		// 向上或向下調整自動下注數
		public function onAutoSwitch(way:Number):void
		{
			this.table.playSound('1000');
			_autoCount++;
			_autoStep = Math.pow(10, Math.floor(_autoCount / 10));
			auto += (way == 1 ? _autoStep : -_autoStep);
		}

		// 調整自動壓注注數
		//public function setAutoSwitch(args:Array):void
		public function setAutoSwitch(way:Number, press:Number):void
		{
			_autoUp = (way == 1 && press == 1);
			_autoDown = (way == 2 && press == 1);
			if (_autoUp || _autoDown)
			{
				_autoStep = 1;
				_autoCount = 0;
				addAutoSwitch();
			}
		}

		public function addAutoSwitch():void
		{
			addCaller(this, {time: TIME_AUTO_STEP, count: 1, onUpdate: doAutoSwitch});
		}

		public function doAutoSwitch():void
		{
			if (_autoUp || _autoDown)
			{
				onAutoSwitch(_autoUp ? 1 : 2);
				addAutoSwitch();
			}
		}

		// 按下滿注（25 線，100 元）
		public function onFullBet(e:MouseEvent):void
		{
			if (_inFreeGame)
			{
				return;
			}
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			line = 25;
			price = 100;
			this.table.playSound('1010');
			onStart();
		}

		public function onStop(e:MouseEvent):void
		{
			var i:Number = 0;
			_autoBet = false;
			// 檢查是否每一行都已經在跑，如果是的話就可以按停
			for (i = 0; i < 5; i++)
			{
				_isHolding = true;
				_slotColumns[i].breakFull();
			}
		}

		public function onStartButton(e:MouseEvent = null):void
		{
			this.table.playSound('1100');
			onStart();
		}

		// 按下【開始】
		public function onStart(e:MouseEvent = null):void
		{
			if (_inFreeGame)
			{
				return;
			}
			_autoBet = (auto > 0);
			_isHolding = false;
			this.table.playSound('1130');
			startBar();
		}

		// 拉動拉把（byUser 表示玩家自已拉的，false 則是小遊戲送的）
		public function startBar():void
		{
			if (state != STATE_PLAY && state != STATE_DEMO)
			{
				return;
			}
			popMessage();
			if (line * price > this.table.menu.money)
			{
				this.table.alert.addAlert('您的金幣不足以下注。',false);
				return;
			}
			this.table.playSound('111' + (int(Math.random() * 2) + 1), 'RunBar');
			line = line;
			state = STATE_RUN;
			clip.btnStart.visible = false;
			clip.btnStop.visible = true;
			_boxReward.number = 0;
			_slotLine.clearLine();
			if (scrolls >= 5)
			{
				scrolls = 0;
			}
			this.core.gold -= _boxTotal.number;
			this.debug.print('>> C2S_Bet：[' + line + ', ' + price + ']');
			this.client.C2S_Bet(line, price);
		}

		// 開始
		public function freeBarStart():void
		{
			this._isGirlFree = true;
			this._slotFree1.reward.number = 0;
			_boxReward.number = 0;
		}

		// 小遊戲贈送拉霸次數
		public function freeBar():void
		{
			//if (state != STATE_FREE) return;
			//this.table.playSound('111' + (int(Math.random() * 2) + 1), 'RunBar');
			this.table.playSound('1110', 'RunBar');
			line = line;
			//state = STATE_RUN;
			clip.btnStart.visible = false;
			clip.btnStop.visible = true;
			//_boxReward.number = 0;
			_slotLine.clearLine();
		}

		public function startFreeGame():void
		{
			_inFreeGame = true;
			switch (this.table.lobby.type)
			{
				case this.table.lobby.TYPE_GIRL:
				{
					this.debug.print('進入拜金女小遊戲');
					_slotFree1.welcome();
					break;
				}
				case this.table.lobby.TYPE_JUNGLE:
				{
					this.debug.print('進入叢林小遊戲');
					_slotFree2.welcome();
					break;
				}
			}
		}

		// 計算並開始展示拉霸成果
		public function countDemo():void
		{
			var jackpots:Number = 0;
			var i:Number        = 0;
			_demoSection = [];
			_demoSection[0] = -1; // 第一個播放所有連線			
			_demoTotal = 1;
			_demoEffect = 1;
			// 先統計總共有幾條線
			for (i = 0; i < _resultCount.length; i++)
			{
				if (_resultCount[i] > 0)
				{
					_demoSection[_demoSection.length] = i;
					_demoTotal++;
				}
			}
			// 再統計是否有中 Jackpot
			for (i = 0; i < _resultColumn.length; i++)
			{
				if (_resultColumn[i] == SYMBOL_JACKPOT)
				{
					jackpots++;
				}
			}
			if (jackpots >= 3)
			{
				_demoSection[_demoSection.length] = -2;
				_demoTotal++;
				_demoEffect = 2;
			}
			if (jackpots >= 7)
			{
				_demoEffect = 3;
			}
			// 總 demo 數量若為 1（表示啥也沒中），就將之改為 -3
			if (_demoSection.length == 1)
			{
				_demoSection[0] = -3;
				_demoEffect = 0;
			}
			else
			{
				this.demoRings();
			}
			_demoCurrent = 0;
			// 拉中需要噴金幣的 jackpot 的話，先表演，時間到後再繼續 doDemo
			if (jackpots >= 7)
			{
				this.main.coin.enable();
				var mc:MovieClip = (this.main.coin.clip.content) as MovieClip;
				mc.oBanner.gotoAndPlay('Start');
				addCaller(this, {time: TIME_COIN_SPRAY, onUpdate: doDemo, count: 1});
				this.table.playSound('1230');
				addCaller(this, {time: TIME_COIN_SOUND, onUpdate: this.table.playSound, onUpdateParams: ['1231'], count: 1});
			}
			else
			{
				doDemo();
			}
		}

		public function addDemo():void
		{
			var continueDemo:Boolean = true;
			state = STATE_DEMO;
			if (_inFreeGame)
			{
				if (this.table.lobby.type == this.table.lobby.TYPE_GIRL)
				{
					addCaller(this, {time: TIME_DEMO_STEP, count: 1, onUpdate: _slotFree1.addBar});
				}
			}
			else
			{
				// 這時如果卷軸已到五支，則改變狀態並開始執行小遊戲
				if (_resultHeart >= 5)
				{
					state = STATE_FREE;
					continueDemo = false;
					addCaller(this, {time: TIME_DEMO_STEP, count: 1, onUpdate: startFreeGame});
				}
				else if (auto > 0 && _autoBet)
				{
					// 繼續自動壓注
					continueDemo = false;
					addCaller(this, {time: TIME_DEMO_STEP, count: 1, onUpdate: startBar});
				}
				if (continueDemo)
				{
					addCaller(this, {time: TIME_DEMO_STEP, count: 1, onUpdate: doDemo});
				}
			}
		}

		public function doDemo():void
		{
			var i:Number        = 0;
			var demoType:Number = _demoSection[_demoCurrent];
			if (state != STATE_DEMO && state != STATE_HARD)
			{
				return;
			}
			normalAllItems();
			switch (demoType)
			{
				/** 所有連線 */
				case -1:
				{
					_resultRound--;
					if (_resultRound > 0)
					{
						switch (_demoEffect)
						{
							case 0:
								break;
							case 1:
							{
								this.table.playSound('1200');
								break;
							}
							case 2:
							{
								this.table.playSound('1210');
								break;
							}
							case 3:
								//this.table.playSound('1230');
								break;
						}
					}
					_slotLine.showLine(_resultCount);
					demoLines(_resultLights);
					break;
				}
				/** Jackpot */
				case -2:
				{
					if (_resultRound > 0)
					{
						this.table.playSound('1201');
					}
					_slotLine.clearLine();
					for (i = 0; i < _resultColumn.length; i++)
					{
						if (_resultColumn[i] == SYMBOL_JACKPOT)
						{
							_slotColumns[int(i % 5)].play(int(i / 5) + 1);
						}
					}
					demoLines([]);
					break;
				}
				/** 沒中 */
				case -3:
					break;
				/** 單線 */
				default:
				{
					if (_resultRound > 0)
					{
						this.table.playSound('1201');
					}
					_slotLine.singleLine(demoType);
					demoLines([demoType]);
					for (i = 0; i < 5; i++)
					{
						if (i < _resultCount[demoType])
						{
							_slotColumns[i].play(_columnMap[demoType][i]);
						}
					}
					break;
				}
			}
			_demoCurrent++;
			if (_demoCurrent >= _demoTotal)
			{
				_demoCurrent = 0;
			}
			popMessage();
			addDemo();
		}

		public function normalAllItems():void
		{
			var i:Number = 0;
			var j:Number = 0;
			for (i = 0; i < 5; i++)
			{
				for (j = 1; j < 4; j++)
				{
					_slotColumns[i].normal(j);
				}
			}
		}

		public function onColumnStock(e:Event):void
		{
			this.table.stopSound('Extra');
			if (e.target.jackpots > 0)
			{
				this.table.playSound('122' + (e.target.index - 1));
				if (e.target.index == 1 || e.target.index == 2)
				{
					this.table.playSound('1140', 'Extra');
				}
			}
			else
			{
				this.table.playSound('1130');
			}
		}

		// 輪盤停下來的後續處理
		//STATE_HARD
		public function onColumnStop(e:Event):void
		{
			process++;
			var i:Number        = 0;
			var allStop:Boolean = true; // 是否跑完
			// 檢查是否每一行都已經在跑，如果是的話就可以按停
			for (i = 0; i < 5; i++)
			{
				if (!_slotColumns[i].ducked)
				{
					allStop = false;
				}
			}
			// 如果每行都已經停下來的話，就開始展示本次拉霸成果
			if (allStop)
			{
				this.table.stopSound('RunBar');
				state = STATE_HARD; // 先設定機台為硬直（一定要展示所有線條）
				clip.btnStart.visible = true;
				clip.btnStop.visible = false;
				scrollTarget = _resultHeart;
				if (this._isGirlFree) // 目前拉出的結果是拜金女小遊戲送的，這樣的話先不要加入總金額中，先放在拉到金額
				{
					this._slotFree1.reward.number += _resultWin; // 贏得獎金直接改為拉到的錢
				}
				else
				{
					_boxReward.number = _resultWin; // 贏得獎金直接改為拉到的錢			
					this.core.gold = _resultNow; // 並增加總金額
				}
				if (!_inFreeGame)
				{
					auto--;
				}
				// 如果這時自動拉霸已經歸零，則停止自動拉霸
				if (auto <= 0)
				{
					_autoBet = false;
				}
				countDemo();
					//popMessage(); // <= 本來要直接展示，不過可能會有 jackpot 訊息，延到 doDemo
					//時比較合理
			}
		}

		// 如果拉霸停下來，或是小遊戲結束，或是沒在跑的話，就可以彈出訊息了
		public function popMessage():void
		{
			this.core.popAlert();
			this.core.popMessage();
			this.core.popToday();
			this.core.popTotal();
		}

		public function addJungleMoney(n:Number):void
		{
			reward = n;
			this.core.gold += n;
		}

		public function onColumnRun(e:Event):void
		{
			if (_isHolding)
			{
				_slotColumns[e.target.index].breakFull();
			}
		}
	/*public function onColumnBreak(e:Event):void
	{
	}*/
	/*public function onColumnDuck(e:Event):void
	{
	}*/
	}
}
